﻿using System;
using NguyenHoa.Web.App_Code;
using System.Data;
using NguyenHoa.Services;
using System.Web;
using System.Web.UI.HtmlControls;
using System.Web.UI;

namespace NguyenHoa.Web.Controls
{
  public partial class SubMenu : BaseControl
  {
    #region Properties
    private string ulStyle = string.Empty;
    private bool m_haveActive = false;
    #endregion

    #region Events
    protected void Page_Load(object sender, EventArgs e)
    {
      if (!Page.IsPostBack && !Page.IsCallback)
      {
        ShowMenu();
      }

      if (Page.IsPostBack)
      {
        if (Request["__EVENTTARGET"] == "FrontLeftMenuChange")
        {
          string[] paras = Request["__EVENTARGUMENT"].Split('|');
          if (paras.Length >= 2)
          {
            SelectedSubMenuItem = paras[0];
            Response.Redirect(paras[1]);
          }
        }
      }
    }
    #endregion

    #region Methods
    private void ShowMenu()
    {
      if (string.IsNullOrEmpty(SelectedMenuItem)) SelectedMenuItem = "0";
      menu.InnerHtml = "";// "<ul class='ul_menu_ver'>";

      SubMenuService menuService = new SubMenuService();
      DataSet ds = menuService.GetSubMenuByLanguage(Convert.ToInt32(SelectedMenuItem), CurrentLanguage.Id, null);
      if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
      {
        SelectedSubMenuItemTitle = SelectedMenuItemTitle;
        if (Page.Master != null)
        {
          Control divMenu = Page.Master.FindControl("submenu1") as Control;
          if (divMenu != null)
          {
            divMenu.Visible = false;
          }
        }
      }
      else
      {
        HttpContext currentContext = HttpContext.Current;
        string path = Request.Url.AbsolutePath;
        if (currentContext != null && currentContext.Items.Contains("HttpContextRewriteURL") && currentContext.Items["HttpContextRewriteURL"] != null)
        {
          path = currentContext.Items["HttpContextRewriteURL"].ToString();
        }

        string currentPage = path.Substring(path.LastIndexOf('/') + 1);
        if (!string.IsNullOrEmpty(Request.QueryString.ToString()))
        {
          currentPage += "?" + Request.QueryString;
        }

        bool isActive;
        menu.InnerHtml += BuildSubMenu(ds.Tables[0], string.Empty, 0, currentPage, out isActive);

        if (!m_haveActive) SelectedSubMenuItemTitle = SelectedMenuItemTitle;
      }
    }

    private string BuildSubMenu(DataTable table, string level, int levelId, string currentPage, out bool isActive)
    {
      string result = string.Empty; isActive = false; levelId += 1;
      foreach (DataRow row1 in table.Rows)
      {
        string tid = currentPage.Substring(currentPage.IndexOf("tid=") + 4, 1);
        string temp = string.Empty, row1Id = row1["Id"].ToString().Trim();
        if (row1Id == tid || row1["Link"].ToString().Trim() == currentPage)
        {
          isActive = true;
          m_haveActive = true;
          SelectedSubMenuItem = row1Id;
          SelectedSubMenuItemTitle = row1["Title"].ToString();
        }
        else
        {
          isActive = false;
        }

        DataSet ds = new SubMenuService().GetSubMenuByParent(Convert.ToInt32(row1["Id"]), CurrentLanguage.Id, row1["Source"] != null ? row1["Source"].ToString() : "");
        if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
        {
          temp = BuildSubMenu(ds.Tables[0], string.Format("_level{0}", levelId), levelId, currentPage, out isActive);
        }

        result += string.Format("<li class='li{0}' onclick='getCurrentElement(\"{1}\",\"{2}\")' >", level, row1["Id"], row1["Link"]);
        result += Address(row1["Id"].ToString(), isActive ? "active" : "", row1["Link"].ToString(), row1["Title"].ToString(), row1["Title"].ToString());
        if (!string.IsNullOrEmpty(temp))
        {
          result += "<div>";
          result += string.Format("<ul class='ul_menu_ver{0}' {1}>", level, ulStyle);
          result += temp;
          result += "</ul>";
          result += "</div>";
        }

        result += "</li>";

      }
      return result;
    }

    private string Address(string id, string classCss, string href, string title, string text)
    {
      string target = string.Empty;
      if (!string.IsNullOrEmpty(href))
      {
        if (Uri.IsWellFormedUriString(href, UriKind.Absolute))
        {
          Uri url = new Uri(href);
          if (url.Host != Request.Url.Host)
          {
            target = "target='_blank' ";
          }
        }
      }

      if (!string.IsNullOrEmpty(classCss))
      {
        return "<a id='" + id + "' class='" + classCss + "' title='" + title + "' " + target + ">" + text + "</a>";
      }
      return "<a id='" + id + "' title='" + title + "' " + target + ">" + text + "</a>";
    }
    #endregion
  }
}